<template>
  <div class="smart-plan-range-container">
    <common-table
      v-if="isInit"
      type="planRange"
      :fields="fields"
      :list-data="listData"
      :total="total"
      :list-loading="loading"
      :create-dimension="createDimension"
      :operation="operation"
      :placeholder="$t('smartPlan.searchNoOrName')"
      :show-select-column="true"
      :storage-key="storageKey"
      @search="handleSearch"
    >
      <div slot="actions" slot-scope="{ row }" v-if="allowEditSmartPlan">
        <!-- <el-button type="text" @click="adjustLinkman(row)">{{ $t('smartPlan.adjustLinkman') }}</el-button> -->
        <el-button type="text" @click="removePlanRange(row)">{{ $t('common.base.remove') }}</el-button>
      </div>
    </common-table>
    <!-- 调整联系人弹窗 -->
    <adjust-linkman-dialog ref="adjustLinkmanDialog" :create-dimension="createDimension" @success="operateSuccess"/>
  </div>
</template>

<script>
import CommonTable from '@src/modules/smartPlan/common/commonTable.vue'
import AdjustLinkmanDialog from './adjustLinkmanDialog'
import { getIntelligentPlanRange, removeIntelligentPlanRange } from '@src/modules/smartPlan/api/index.js'
import { handleOperation } from '@src/modules/smartPlan/util/index.js'
import { getCustomerFields } from '@src/api/CustomerApi'
import { getProductFields } from '@src/api/ProductApi'
import { convertQualityInfoRemoteDataToFormQualityInfoFieldValue } from '@service/QualityInfoService.ts'
import { t } from '@src/locales'

export default {
  // 计划范围
  name: 'smart-plan-range',
  props: {
    planId: {
      type: String,
      default: ''
    },
    createDimension: {
      type: [String, Number],
      default: 0
    },
    allowEditSmartPlan: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      isInit: false,
      fields: [],
      listData: [],
      loading: false,
      total: 0,
    }
  },
  computed: {
    storageKey() {
      return `smartPlanRange_${this.createDimension}`
    },
    operation() {
      if (this.allowEditSmartPlan) {
        return {
          isShow: true,
        }
      }
      return {}
    }
  },
  async mounted() {
    await this.getFields()
    this.getList()
  },
  methods: {
    handleSearch(params) {
      this.getList(params)
    },
    buildParams() {
      return {
        pageNum: 1,
        pageSize: 10,
      }
    },
    getList(params) {
      const searchParams = {
        id: this.planId,
        ...this.buildParams(),
        ...params
      }
      this.loading = true
      getIntelligentPlanRange(searchParams).then(res => {
        this.loading = false
        this.listData = (res.data?.list || []).map(item => {
          return {
            ...Object.assign(item, convertQualityInfoRemoteDataToFormQualityInfoFieldValue(item, true)),
            ...item.attribute
          }
        })
        this.total = res.data?.total || 0
      })
    },
    async getFields() {
      let res = null
      if (this.createDimension == 0) {
        res = await getProductFields({isFromSetting: false})
        const customerField = res?.data?.filter(f => f.formType == 'customer')[0]
        const customerIndex = res?.data?.findIndex(f => f.formType == 'customer')
        if (customerField && customerField.setting?.customerOption?.linkman) {
          res.data.splice(customerIndex + 1, 0, {
            displayName: t('common.base.contact'),
            fieldName: 'linkman',
            isSystem: 1,
            tableName: 'product'
          }, {
            displayName: t('common.base.phone'),
            fieldName: 'phone',
            isSystem: 1,
            tableName: 'product'
          })
        }
        if (customerField && customerField.setting?.customerOption?.address) {
          res.data.splice(customerIndex + 1, 0, {
            displayName: t('common.form.type.customerAddress'),
            fieldName: 'customerAddress',
            isSystem: 1,
            tableName: 'product'
          })
        }
      } else if (this.createDimension == 1) {
        res = await getCustomerFields({isFromSetting: false})
        if (res.data && res.data.length) {
          const customerIndex = res.data.findIndex(f => f.formType == 'customer')
          res.data.splice(customerIndex + 1, 0, {
            displayName: t('common.label.customerTag'),
            fieldName: 'customerTag',
            isSystem: 1,
            tableName: 'customer',
          })
        }
      }
      this.isInit = true
      this.fields = res.data || []
    },
    removePlanRangeSuccess() {
      this.getList()
      this.$emit('updateDynamicInfo')
    },
    // 移除计划范围
    removePlanRange(row) {
      handleOperation(
        removeIntelligentPlanRange,
        {
          id: this.planId,
          objectId: row.id,
          objectName: row.name
        },
        t('smartPlan.tips.tip4'),
        this.removePlanRangeSuccess
      )
    },
    // 调整联系人
    adjustLinkman(row) {
      row.planId = this.planId
      this.$refs.adjustLinkmanDialog.openDialog(row)
    },
    operateSuccess() {
      this.getList()
      this.$emit('updateDynamicInfo')
    },
  },
  components: {
    CommonTable,
    AdjustLinkmanDialog,
  },
}
</script>

<style>

</style>